<!DOCTYPE html>
<html>
<head>
    <title>EMQX Camera Stream</title>
    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
    <style>
        #videoFeed {
            width: 320px;
            height: 240px;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <h1>Live Camera Stream via EMQX</h1>
    <img id="videoFeed" src="" alt="Camera Feed">
    <p>FPS: <span id="fps">0</span></p>

    <script>
        // MQTT 配置
        const broker = 'ws://120.46.12.5:8083/mqtt'; // EMQX WebSocket 地址
        const topic = 'camera/encode_transfrom';
        const client = mqtt.connect(broker, {
            username: 'gll',
            password: 'gll55555',
            clientId: 'web_viewer_' + Math.random().toString(16).substr(2, 8)
        });

        let frameCount = 0;
        let fpsStart = Date.now();

        // 计算 FPS
        function calculateFPS() {
            frameCount++;
            const elapsed = (Date.now() - fpsStart) / 1000;
            if (elapsed >= 1) {
                const fps = frameCount / elapsed;
                document.getElementById('fps').textContent = fps.toFixed(2);
                frameCount = 0;
                fpsStart = Date.now();
            }
        }

        // 连接成功
        client.on('connect', () => {
            console.log('Connected to EMQX broker');
            client.subscribe(topic, { qos: 0 }, (err) => {
                if (!err) {
                    console.log(`Subscribed to ${topic}`);
                } else {
                    console.error('Subscription failed:', err);
                }
            });
        });

        // 接收消息并更新图片
        client.on('message', (topic, message) => {
            const payload = JSON.parse(message.toString());
            const imgElement = document.getElementById('videoFeed');
            imgElement.src = 'data:image/jpeg;base64,' + payload.image;
            calculateFPS();
        });

        // 错误处理
        client.on('error', (err) => {
            console.error('MQTT Error:', err);
        });

        client.on('close', () => {
            console.log('Disconnected from EMQX');
        });
    </script>
</body>
</html>
